package com.runfast.waimai.web.controller.order;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.OrderExample;
import com.runfast.paotui.dao.model.OrderStatusHistory;
import com.runfast.paotui.service.OrderService;
import com.runfast.paotui.service.OrderStatusHistoryService;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.TimeUtil;
import com.runfast.waimai.utils.WaiMaiMessagePushTask;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import java.util.*;

import static com.runfast.paotui.dao.model.Order.Status.COMPLETED;
import static com.runfast.paotui.dao.model.Order.Status.PICKED;
import static com.runfast.paotui.dao.model.Order.Status.TAKEN;

/**
 * ${DESCRIPTION}订单管理
 *
 * @author chenzheng
 * @create 2018-05-08 22:23
 **/
@RestController("orderController")
@RequestMapping("/server/order")
public class OrderController {
    @Autowired
    private RunfastGoodsSellRecordService runfastGoodsSellRecordService;
    @Autowired
    private RunfastGoodsSellChildrenService runfastGoodsSellChildrenService;
    @Autowired
    private RunfastGoodsSellOutStatusService runfastGoodsSellOutStatusService;
    @Autowired
    private WaiMaiRunfastCuserService waiMaiRunfastCuserService;
    @Autowired
    private WaiMaiRunfastShopperService waiMaiRunfastShopperService;
    @Autowired
    private WaiMaiRunfastCuseraddressService waiMaiRunfastCuseraddressService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private WaiMaiRunfastDeliverCostService waiMaiRunfastDeliverCostService;
    @Autowired
    private WaiMaiMessagePushTask waiMaiMessagePushTask;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderStatusHistoryService orderStatusHistoryService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    /**
     * 订单列表带分页的
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable, RunfastGoodsSellRecord record){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        Map<Object,Object> map=new HashMap<Object, Object>();
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(record!=null){
            if(StringUtils.isNotBlank(record.getBusinessname())){
                map1.put("businessName",record.getBusinessname());
            }
            if(StringUtils.isNotBlank(record.getUsermobile())){
                map1.put("userMobile",record.getUsermobile());
            }
            if(StringUtils.isNotBlank(record.getOrdercode())){
                map1.put("orderCode",record.getOrdercode());
            }
            if(record.getSelectOrderTime()!=null){
                map1.put("selectOrderTime",record.getSelectOrderTime());
            }
            if(record.getSelectOrderStatus()!=null){
                map1.put("selectOrderStatus",record.getSelectOrderStatus());
            }
        }
        if(admin!=null && admin.getType()==3 && accounts!=null){
            //商家帐号登录----只能看自己商家的
            map1.put("businessId",accounts.getBusinessid());
        }else if(admin!=null  &&admin.getType()==2  && agentAccounts!=null){
            //代理商登录
            map1.put("agentIds",agentAccounts.getAgentid());
        }else if(admin !=null && admin.getType()==1){
            //后台管理员---查看全部的
            if(StringUtils.isNotBlank(record.getAgentIds())){
                map1.put("agentIds",record.getAgentIds());
            }else{
                if(admin.getAgents().size()>0){
                    map1.put("agentIds",  StringUtils.join(admin.getAgents().toArray(), ","));
                }
            }
        }
        map1.put("pageable",pageable);
        List<RunfastGoodsSellRecord> list=runfastGoodsSellRecordService.selectByMapWithPageable(map1);
        if(list.size()>0){
            for(RunfastGoodsSellRecord record1:list){
               if(record1.getAgentid()!=null){
                   WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(record1.getAgentid());
                   if(agentbusiness!=null){
                       record1.setAgentname(agentbusiness.getName());
                   }
               }
            }
        }
        Integer total=runfastGoodsSellRecordService.countByMap(map1);
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

     /**
      * 订单信息
     */
    @GetMapping("/info")
    public Result info(Integer id){
        if(id==null){return Result.fail(null,"订单id不能为空!");}
        RunfastGoodsSellRecord goodsSellRecord =runfastGoodsSellRecordService.selectByPrimaryKey(id);
        if(goodsSellRecord !=null){
            //子订单信息
            RunfastGoodsSellChildrenExample example=new RunfastGoodsSellChildrenExample();
            example.createCriteria().andOrdercodeEqualTo(goodsSellRecord.getOrdercode());
            List<RunfastGoodsSellChildren> childrens = runfastGoodsSellChildrenService.selectByExample(example);
            //订单状态改变表--订单进度
            RunfastGoodsSellOutStatusExample example1=new RunfastGoodsSellOutStatusExample();
            example1.createCriteria().andGoodssellrecordcodeEqualTo(goodsSellRecord.getOrdercode());
            List<RunfastGoodsSellOutStatus> status=runfastGoodsSellOutStatusService.selectByExample(example1);
            //客户信息
            if(goodsSellRecord.getUserid()!=null){
                WaiMaiRunfastCuser cuser = waiMaiRunfastCuserService.selectByPrimaryKey(goodsSellRecord.getUserid());
                if(cuser!=null){
                    goodsSellRecord.setCuser(cuser);
                }
            }
            //客户地址信息
            if(goodsSellRecord.getUseraddressid()!=null){
                WaiMaiRunfastCuseraddress  cuseraddress=waiMaiRunfastCuseraddressService.selectByPrimaryKey(goodsSellRecord.getUseraddressid());
                if(cuseraddress!=null){
                    goodsSellRecord.setCuseraddress(cuseraddress);
                }
            }
            if(goodsSellRecord.getAgentid()!=null){
                WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(goodsSellRecord.getAgentid());
                if(agentbusiness!=null){
                    goodsSellRecord.setAgentname(agentbusiness.getName());
                }
            }
            goodsSellRecord.setGoodsSellRecordChildren(childrens);
            goodsSellRecord.setGoodsSellOutStatus(status);
        }
        return Result.ok(null,goodsSellRecord);
    }
    /**
     * 修改订单状态
     * */
    @GetMapping("/editOrderStatus")
    public  Result editOrderStatus(RunfastGoodsSellRecord goodsSellRecord) {
        String  message=null;
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
            if(goodsSellRecord!=null && goodsSellRecord.getId()!=null && goodsSellRecord.getStatus()!=null){
                RunfastGoodsSellRecord t  = runfastGoodsSellRecordService.selectByPrimaryKey(goodsSellRecord.getId());
                //添加操作记录
                RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                //操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
                if(admin!=null && admin.getType()==3&&  accounts!=null){
                    //商家帐号登录
                    goodsSellOutStatus.setType(1);
                    goodsSellOutStatus.setOperationid(accounts.getId());
                    goodsSellOutStatus.setOperationname(accounts.getName());
                }else if(admin!=null  && admin.getType()==2 && agentAccounts !=null){
                    //代理商
                    goodsSellOutStatus.setType(4);
                    goodsSellOutStatus.setOperationid(agentAccounts.getId());
                    goodsSellOutStatus.setOperationname(agentAccounts.getName());
                }else if(admin !=null &&  admin.getType()==1){//后台管理员
                    goodsSellOutStatus.setType(0);
                    goodsSellOutStatus.setOperationid(admin.getId());
                    goodsSellOutStatus.setOperationname(admin.getUsername());
                }
                if(goodsSellRecord.getStatus()==4){
                    goodsSellOutStatus.setSort(4);//状态
                    goodsSellOutStatus.setBusinessid(t.getBusinessid());//商家
                    goodsSellOutStatus.setBusinessname(t.getBusinessname());
                    goodsSellOutStatus.setGoodssellrecordcode(t.getOrdercode());//订单号
                    goodsSellOutStatus.setGoodssellrecordid(t.getId());//订单id
                    goodsSellOutStatus.setCreatetime(new Date());
                    goodsSellOutStatus.setStatstr("商品打包");
                    runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                    t.setStatus(4);
                    t.setStatstr("商品打包");
                    message="商品打包!";
                }else if(goodsSellRecord.getStatus()==5){
                    goodsSellOutStatus.setSort(5);//状态
                    goodsSellOutStatus.setBusinessid(t.getBusinessid());//商家
                    goodsSellOutStatus.setBusinessname(t.getBusinessname());
                    goodsSellOutStatus.setGoodssellrecordcode(t.getOrdercode());//订单号
                    goodsSellOutStatus.setGoodssellrecordid(t.getId());//订单id
                    goodsSellOutStatus.setCreatetime(new Date());
                    goodsSellOutStatus.setStatstr("商品配送");
                    runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                    t.setStatus(5);
                    t.setStatstr("商品配送");
                    message="商品配送!";
                }else if(goodsSellRecord.getStatus()==8){
                    goodsSellOutStatus.setSort(8);//状态
                    goodsSellOutStatus.setBusinessid(t.getBusinessid());//商家
                    goodsSellOutStatus.setBusinessname(t.getBusinessname());
                    goodsSellOutStatus.setGoodssellrecordcode(t.getOrdercode());//订单号
                    goodsSellOutStatus.setGoodssellrecordid(t.getId());//订单id
                    goodsSellOutStatus.setCreatetime(new Date());
                    goodsSellOutStatus.setStatstr("订单完成");
                    runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                    t.setStatus(8);
                    t.setStatstr("订单完成");
                    message="订单完成!";
                }
                runfastGoodsSellRecordService.updateByPrimaryKeySelective(t);
                //if(diaoDuWebsocketController.webSockets !=null &&diaoDuWebsocketController.webSockets.size()>0){
                    //diaoDuWebsocketController.broadcast(t, null,null);
                amqpTemplate.convertAndSend("waimaiServer_order_exchange", "", JSON.toJSONString(t));
                //}
                waiMaiMessagePushTask.takenOrderToCustomer(t.getOrdercode(),t.getUserid(),message);
            }else{return Result.fail(null,"传入参数不对！");}
      return  Result.ok(null);
    }


    /**
     *给骑手派单（新单第一次指派）
     * */
    @PostMapping("/setRiderOrder")
    public Result setRiderOrder(@RequestBody RunfastGoodsSellRecord goodsSellRecord){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        if(goodsSellRecord.getIds().size()>0  && goodsSellRecord.getShopperid()!=null) {
            WaiMaiRunfastShopper shopper = waiMaiRunfastShopperService.selectByPrimaryKey(goodsSellRecord.getShopperid());
            if(shopper!=null){
                for(Integer s:goodsSellRecord.getIds()){
                    RunfastGoodsSellRecord t=runfastGoodsSellRecordService.selectByPrimaryKey(s);
                    if(t!=null){
                            if(agentAccounts!=null&&!agentAccounts.getAgentid().equals(t.getAgentid())){
                                return  Result.fail(null,"只能修改自己名下商家的订单！");
                            }
                            if(shopper!=null && (shopper.getStatus()!=null && shopper.getStatus()==-1) && (shopper.getWorking()!=null && shopper.getWorking()!=1)){
                                return  Result.fail(null,"骑手无法接单，请另选一个！");
                            }
                            if(t.getIsdeliver()!=null && t.getIsdeliver()==1){
                                //商家自配送
                                return Result.fail(null,"订单为商家自配送，不能指派骑手！");
                            }
                            if(t.getSuportself()!=null && t.getSuportself()==true){
                                //客户自取
                                return Result.fail(null,"订单为客户自取，不能指派骑手！");
                            }
                            if(t.getShopperid()!=null){
                                return Result.fail(null,"已经有骑手接单，不能再指派骑手！");
                            }
                            if(shopper.getDistributionmun()==null){
                                shopper.setDistributionmun(5);
                            }
                            RunfastGoodsSellRecordExample recordExample2=new RunfastGoodsSellRecordExample();
                            recordExample2.createCriteria().andShopperidEqualTo(shopper.getId()).andStatusBetween(1,7).andCreatetimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                            Integer totalNum2=runfastGoodsSellRecordService.countByExample(recordExample2);
                            OrderExample recordExample3=new OrderExample();
                            List<Integer> s1=new ArrayList<Integer>();
                            s1.add(3);
                            s1.add(5);
                            recordExample3.createCriteria().andDriverIdEqualTo(shopper.getId()).andStatusIn(s1).andCreateTimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                            Integer totalNum3=orderService.countByExample(recordExample3);
                            Integer totalNum=0;
                            totalNum=totalNum2+totalNum3;
                            if(shopper.getDistributionmun()<=totalNum){
                               return Result.fail(null,"已达到该骑手当日最大配送量（"+shopper.getDistributionmun()+"单），不能再给该骑手派单！");
                            }
                            t.setShopper(shopper.getName());
                            t.setShopperid(shopper.getId());
                            t.setShoppermobile(shopper.getMunber());
                            if(t.getStatus()!=2){//商家未接单
                                t.setStype(1);
                            }else if(t.getStatus()==2){//商家已接单
                                t.setStatus(3);
                                t.setStatstr("骑手接单");
                            }
                            RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                            goodsSellOutStatus.setBusinessid(t.getBusinessid());
                            goodsSellOutStatus.setBusinessname(t.getBusinessname());
                            goodsSellOutStatus.setCreatetime(new Date());
                            goodsSellOutStatus.setGoodssellrecordcode(t.getOrdercode());
                            goodsSellOutStatus.setGoodssellrecordid(t.getId());
                            goodsSellOutStatus.setGoodssellrecordname(t.getGoodssellname());
                            //操作人类型 0：后台管理员， 2:快递员  ，3：用户,4 代理商
                            if(admin!=null && admin.getType()==2 && agentAccounts !=null){//代理商
                                goodsSellOutStatus.setType(4);
                                goodsSellOutStatus.setOperationid(agentAccounts.getId());
                                goodsSellOutStatus.setOperationname(agentAccounts.getName());
                            }else if(admin !=null && admin.getType()==1){//后台管理员
                                goodsSellOutStatus.setType(0);
                                goodsSellOutStatus.setOperationid(admin.getId());
                                goodsSellOutStatus.setOperationname(admin.getUsername());
                            }
                            goodsSellOutStatus.setSort(-5);
                            goodsSellOutStatus.setStatstr("指派骑手");
                            RunfastGoodsSellOutStatusExample example=new RunfastGoodsSellOutStatusExample();
                            example.createCriteria().andGoodssellrecordcodeEqualTo(t.getOrdercode());
                            runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                            runfastGoodsSellRecordService.updateByPrimaryKeySelective(t);
                        //if(diaoDuWebsocketController.webSockets !=null &&diaoDuWebsocketController.webSockets.size()>0){
                            //diaoDuWebsocketController.broadcast(t, null,null);
                            //diaoDuWebsocketController.broadcast(null, shopper,null);
                        amqpTemplate.convertAndSend("waimaiServer_order_exchange", "", JSON.toJSONString(t));
                        amqpTemplate.convertAndSend("server_shopper_exchange", "", JSON.toJSONString(shopper));
                       // }
                        waiMaiMessagePushTask.takenOrderToCustomer(t.getOrdercode(),t.getUserid(),"骑手已接单！");
                        waiMaiMessagePushTask.takenOrderToShopper(t.getOrdercode(),shopper.getId(),"已经派单给您！");
                    }
                }
            }else{return Result.fail(null,"找不到对应的骑手！");}
        }else{return Result.fail(null,"订单id，或骑手id为空！");}
       return  Result.ok(null);
    }

    /**
     *改派骑手（已经有所属的骑手但其未接单：改派）
     * */
    @GetMapping("/editOrderRider")
   public Result editOrderRider(RunfastGoodsSellRecord goodsSellRecord){
        WaiMaiRunfastShopper shopper1=new WaiMaiRunfastShopper();
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        if(goodsSellRecord!=null && goodsSellRecord.getId()!=null&& goodsSellRecord.getShopperid()!=null){
            shopper1 = waiMaiRunfastShopperService.selectByPrimaryKey(goodsSellRecord.getShopperid());
            if(shopper1!=null){
                goodsSellRecord.setShopper(shopper1.getName());
                goodsSellRecord.setShoppermobile(shopper1.getMunber());
            }
        }
        if(goodsSellRecord!=null && goodsSellRecord.getId()!=null&& goodsSellRecord.getShopperid()!=null ){
            RunfastGoodsSellRecord t  = runfastGoodsSellRecordService.selectByPrimaryKey(goodsSellRecord.getId());

            if(t!=null && t.getShopperid()!=null && goodsSellRecord.getShopperid()!=null&&t.getStatus()!=null&&t.getStatus()>2&&t.getStatus()<6){

                if(agentAccounts!=null&&!agentAccounts.getAgentid().equals(t.getAgentid())){
                    return  Result.fail(null,"只能修改自己名下商家的订单！");
                }
                if(!t.getShopperid().equals(goodsSellRecord.getShopperid())){
                    WaiMaiRunfastShopper shopper = waiMaiRunfastShopperService.selectByPrimaryKey(t.getShopperid());
                    if(shopper1!=null && (shopper1.getStatus()!=null && shopper1.getStatus()==-1) && (shopper1.getWorking()!=null && shopper1.getWorking()!=1)){
                        return  Result.fail(null,"骑手无法接单，请另选一个！");
                    }
                    RunfastGoodsSellRecordExample recordExample2=new RunfastGoodsSellRecordExample();
                    recordExample2.createCriteria().andShopperidEqualTo(shopper1.getId()).andStatusBetween(1,7).andCreatetimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                    Integer totalNum2=runfastGoodsSellRecordService.countByExample(recordExample2);
                    OrderExample recordExample3=new OrderExample();
                    List<Integer> s1=new ArrayList<Integer>();
                    s1.add(3);
                    s1.add(5);
                    recordExample3.createCriteria().andDriverIdEqualTo(shopper1.getId()).andStatusIn(s1).andCreateTimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                    Integer totalNum3=orderService.countByExample(recordExample3);
                    Integer totalNum=0;
                    totalNum=totalNum2+totalNum3;
                    if(shopper1.getDistributionmun()<=totalNum){
                        return Result.fail(null,"已达到该骑手当日最大配送量（"+shopper1.getDistributionmun()+"单），不能再给该骑手派单！");
                    }
                    /*if(goodsSellRecord.getShopperid()!=null){
                         if(goodsSellRecord.getShopperid().equals(shopper.getId())){
                              return Result.fail(null,"自己的订单不能改派给自己！");
                         }
                    }*/
                    //将原来的配送员设置为原有配送员，更换新的现有配送员
                    t.setOldshopper(t.getShopper());
                    t.setOldshopperid(t.getShopperid());
                    t.setOldshoppermobile(t.getShoppermobile());
                    t.setShopper(goodsSellRecord.getShopper());
                    t.setShopperid(goodsSellRecord.getShopperid());
                    t.setShoppermobile(goodsSellRecord.getShoppermobile());

                    RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                    goodsSellOutStatus.setBusinessid(t.getBusinessid());
                    goodsSellOutStatus.setBusinessname(t.getBusinessname());
                    goodsSellOutStatus.setCreatetime(new Date());
                    goodsSellOutStatus.setGoodssellrecordcode(t.getOrdercode());
                    goodsSellOutStatus.setGoodssellrecordid(t.getId());
                    goodsSellOutStatus.setGoodssellrecordname(t.getGoodssellname());

                    //操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4 代理商
                    if(accounts!=null){//商家帐号登录
                        goodsSellOutStatus.setType(1);
                        goodsSellOutStatus.setOperationid(accounts.getId());
                        goodsSellOutStatus.setOperationname(accounts.getName());

                    }else if(agentAccounts !=null){//代理商

                        goodsSellOutStatus.setType(4);
                        goodsSellOutStatus.setOperationid(agentAccounts.getId());
                        goodsSellOutStatus.setOperationname(agentAccounts.getName());
                    }else if(admin !=null && admin.getType()==1){//后台管理员

                        goodsSellOutStatus.setType(0);
                        goodsSellOutStatus.setOperationid(admin.getId());
                        goodsSellOutStatus.setOperationname(admin.getUsername());
                    }

                    goodsSellOutStatus.setSort(-4);
                    goodsSellOutStatus.setStatstr("骑手更换");

                    RunfastGoodsSellOutStatusExample example=new RunfastGoodsSellOutStatusExample();
                    example.createCriteria().andGoodssellrecordcodeEqualTo(t.getOrdercode());
                   runfastGoodsSellOutStatusService.insertSelective(goodsSellOutStatus);
                }else{
                    return  Result.fail(null,"自己的订单不能改派给自己！");
                }
            }else{
                return  Result.fail(null,"您没有更换到骑手！");
            }
            runfastGoodsSellRecordService.updateByPrimaryKeySelective(t);
            //if(diaoDuWebsocketController.webSockets !=null &&diaoDuWebsocketController.webSockets.size()>0){
                //diaoDuWebsocketController.broadcast(t, null,null);
            amqpTemplate.convertAndSend("waimaiServer_order_exchange", "", JSON.toJSONString(t));
            amqpTemplate.convertAndSend("server_shopper_exchange", "", JSON.toJSONString(shopper1));
            //}
            waiMaiMessagePushTask.takenOrderToCustomer(t.getOrdercode(),t.getUserid(),"已为您更换骑手！");
            waiMaiMessagePushTask.takenOrderToShopper(t.getOrdercode(),t.getShopperid(),"已经派单给您！");
        }
        return  Result.ok(null);
    }
    /**订单调度页面*/
    @GetMapping("/orderSchedulingList")
    public  Result orderSchedulingList(){
        //订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
        //待指派，配送中，异常，超时
        //待指派--商家未接单或骑手未接单
        //代理商登录就是该代理商下所有的订单，后台登录要先指定代理商
        //list1---待指派
        List<RunfastGoodsSellRecord> list1=new ArrayList<RunfastGoodsSellRecord>();
        //list2---配送中
        List<RunfastGoodsSellRecord> list2=new ArrayList<RunfastGoodsSellRecord>();
        //list3--异常
        List<RunfastGoodsSellRecord> list3=new ArrayList<RunfastGoodsSellRecord>();
        //list4--超时
        List<RunfastGoodsSellRecord> list4=new ArrayList<RunfastGoodsSellRecord>();
        WaiMaiRunfastAgentbusiness agentbusiness=new WaiMaiRunfastAgentbusiness();
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        Map<Object,Object> map1=new HashMap<Object, Object>();
        Map<Object,Object> map2=new HashMap<Object, Object>();
        Map<Object,Object> map3=new HashMap<Object, Object>();
        Map<Object,Object> map4=new HashMap<Object, Object>();
        if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商登录
            agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
            if(agentbusiness!=null){
                map1.put("agentId",agentAccounts.getAgentid());
                map2.put("agentId",agentAccounts.getAgentid());
                map3.put("agentId",agentAccounts.getAgentid());
                map4.put("agentId",agentAccounts.getAgentid());
                WaiMaiRunfastDeliverCostExample example1=new WaiMaiRunfastDeliverCostExample();
                example1.createCriteria().andAgentidEqualTo(agentAccounts.getAgentid()).andIsdefaultEqualTo(1);
                List<WaiMaiRunfastDeliverCost> deliverCostList =waiMaiRunfastDeliverCostService.selectByExample(example1);
                if(deliverCostList.size()>0){
                    if(deliverCostList.get(0).getStarttimeday1()!=null && deliverCostList.get(0).getEndtimeday1()!=null){
                        agentbusiness.setFirstTime(TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getStarttimeday1())+","+TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getEndtimeday1()));
                    }
                    if(deliverCostList.get(0).getStarttimenight2()!=null && deliverCostList.get(0).getEndtimenight2()!=null){
                        agentbusiness.setSecondTime(TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getStarttimenight2())+","+TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getEndtimenight2()));
                    }
                }
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else if(admin !=null && admin.getType()==1){
            //后台登录---获取代理商list中第一个
        }
        /**selectType:1待指派，2配送中，3异常，4超时*/
        map1.put("selectType",1);
        list1=runfastGoodsSellRecordService.selectByMapDiaoDu(map1);
        map2.put("selectType",2);
        list2=runfastGoodsSellRecordService.selectByMapDiaoDu(map2);
        map3.put("selectType",3);
        list3=runfastGoodsSellRecordService.selectByMapDiaoDu(map3);
        map4.put("selectType",4);
        list4=runfastGoodsSellRecordService.selectByMapDiaoDu(map4);
        //是否支付； 1：已支付， 其他未支付---isPay
        //用户提出取消订单 1:用户提出 2:商家同意取消订单3:不同意取消订单-----isCancel
        //配送中---骑手接单（待到店，待取餐，待送达）
        //异常-----用户申请退款（商家或后台都未处理）
        //超时
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list1",list1);
        map.put("list2",list2);
        map.put("list3",list3);
        map.put("list4",list4);
        map.put("total1",list1.size());
        map.put("total2",list2.size());
        map.put("total3",list3.size());
        map.put("total4",list4.size());
        map.put("agentbusiness",agentbusiness);
        return Result.ok(null,map);
    }

    /**抢单，指派模式的切换-----要解决一个问题：关闭订单调度的时候如果还是为派单模式则要想办法给为抢单模式*/
    @GetMapping("/setOrderModel")
    public Result setOrderModel(WaiMaiRunfastAgentbusiness agentbusiness1){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        if(admin!=null && admin.getType()==2 && agentAccounts!=null && agentAccounts.getAgentid()!=null){
            if(agentbusiness1!=null && agentbusiness1.getOrderMode()!=null){
                WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
                if(agentbusiness==null){ return Result.fail(null,"未找到对应的代理商！");}
                if(agentbusiness!=null){
                    agentbusiness.setOrderMode(agentbusiness1.getOrderMode());
                    waiMaiRunfastAgentbusinessService.updateByPrimaryKeySelective(agentbusiness);
                }
            }else{return Result.fail(null,"代理商的id及订单的模式不能为空！");}
        }else{return  Result.fail(null,"此功能只有代理商才有！");}
        return  Result.ok(null);
    }


    public void setOrderModel1() {
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts = SessionContext.getCurrentRunfastAgentaccounts();
        if (admin != null && admin.getType() == 2 && agentAccounts != null && agentAccounts.getAgentid() != null) {
                WaiMaiRunfastAgentbusiness agentbusiness = waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
                if (agentbusiness != null) {
                    agentbusiness.setOrderMode(1);
                    waiMaiRunfastAgentbusinessService.updateByPrimaryKeySelective(agentbusiness);
                }
        }
    }

   /**替商家接单或者拒单*/
   //订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
   @PostMapping("setRecordStatus")
   @Transactional
   public Result setRecordStatus(@RequestBody RunfastGoodsSellRecord goodsSellRecord){
       BaseUser admin = SessionContext.getAdmin();
       WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
       if(goodsSellRecord!=null && goodsSellRecord.getStatusType()!=null && goodsSellRecord.getIds().size()>0){
            if(goodsSellRecord.getStatusType()==1){
                //接单
                for(Integer id:goodsSellRecord.getIds()){
                    RunfastGoodsSellRecord goodsSellRecord1=runfastGoodsSellRecordService.selectByPrimaryKey(id);
                    if(goodsSellRecord1!=null){
                        if(goodsSellRecord1.getStatus()>=2){
                           return Result.fail(null,"订单号为："+goodsSellRecord1.getOrdercode()+"的订单已经接单！");
                        }else if(goodsSellRecord1.getStatus()==1){
                            if(goodsSellRecord1.getShopperid()!=null){
                                //骑手已经接单
                                goodsSellRecord1.setStatus(3);//商家接单
                                goodsSellRecord1.setStatstr("骑手接单");
                            }else{
                                //骑手未接单
                                goodsSellRecord1.setStatus(2);//商家接单
                                goodsSellRecord1.setStatstr("商家接单");
                            }
                            goodsSellRecord1.setAcepttime(new Date());
                            //添加操作记录
                            RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                            //操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
                            if(admin!=null && admin.getType()==2 && agentAccounts !=null){
                                //代理商
                                goodsSellOutStatus.setType(4);
                                goodsSellOutStatus.setOperationid(agentAccounts.getId());
                                goodsSellOutStatus.setOperationname(agentAccounts.getName());
                            }
                            goodsSellOutStatus.setSort(goodsSellRecord1.getStatus());//状态
                            if(goodsSellRecord1.getStatus()!=null){
                                //订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：商品打包 ， 4：商品配送 5：商品送达，6:确认收货 ，7：订单完成
                                if(goodsSellRecord1.getStatus()==2){
                                    goodsSellOutStatus.setStatstr("商家接单");
                                }
                            }
                            goodsSellOutStatus.setBusinessid(goodsSellRecord1.getBusinessid());//商家
                            goodsSellOutStatus.setBusinessname(goodsSellRecord1.getBusinessname());
                            goodsSellOutStatus.setGoodssellrecordcode(goodsSellRecord1.getOrdercode());//订单号
                            goodsSellOutStatus.setGoodssellrecordid(goodsSellRecord1.getId());//订单id
                            goodsSellOutStatus.setCreatetime(new Date());
                            RunfastGoodsSellOutStatusExample example=new RunfastGoodsSellOutStatusExample();
                            example.createCriteria().andGoodssellrecordcodeEqualTo(goodsSellRecord1.getOrdercode());
                            runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                            runfastGoodsSellRecordService.updateByPrimaryKeySelective(goodsSellRecord1);
                            //if(diaoDuWebsocketController.webSockets !=null &&diaoDuWebsocketController.webSockets.size()>0){
                                //diaoDuWebsocketController.broadcast(goodsSellRecord1, null,null);
                            amqpTemplate.convertAndSend("waimaiServer_order_exchange", "", JSON.toJSONString(goodsSellRecord1));
                            //}
                            waiMaiMessagePushTask.takenOrderToBusiness(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getBusinessid(),"平台已为您接单！");
                            waiMaiMessagePushTask.takenOrderToCustomer(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getUserid(),"商家已接单！");
                            if(goodsSellRecord1.getShopperid()!=null){
                                waiMaiMessagePushTask.takenOrderToShopper(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getShopperid(),"商家已接单！");
                            }
                        }
                    }
                }
            }else if(goodsSellRecord.getStatusType()==2){
                //拒单
                for(Integer id:goodsSellRecord.getIds()){
                    RunfastGoodsSellRecord goodsSellRecord1=runfastGoodsSellRecordService.selectByPrimaryKey(id);
                    if(goodsSellRecord1!=null){
                        if(goodsSellRecord1.getStatus()>=2){
                            return Result.fail(null,"订单号为："+goodsSellRecord1.getOrdercode()+"的订单已经接单！");
                        }else if(goodsSellRecord1.getStatus()==1){
                            goodsSellRecord1.setStatus(-3);//商家拒单
                            goodsSellRecord1.setStatstr("商家拒单");
                            //添加操作记录
                            RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                            //操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
                            if(admin!=null && admin.getType()==2 && agentAccounts !=null){
                                //代理商
                                goodsSellOutStatus.setType(4);
                                goodsSellOutStatus.setOperationid(agentAccounts.getId());
                                goodsSellOutStatus.setOperationname(agentAccounts.getName());
                            }
                            goodsSellOutStatus.setSort(goodsSellRecord1.getStatus());//状态
                            if(goodsSellRecord1.getStatus()!=null){
                                //订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：商品打包 ， 4：商品配送 5：商品送达，6:确认收货 ，7：订单完成
                                if(goodsSellRecord1.getStatus()==-3){
                                    goodsSellOutStatus.setStatstr("商家拒单");
                                }
                            }
                            goodsSellOutStatus.setBusinessid(goodsSellRecord1.getBusinessid());//商家
                            goodsSellOutStatus.setBusinessname(goodsSellRecord1.getBusinessname());

                            goodsSellOutStatus.setGoodssellrecordcode(goodsSellRecord1.getOrdercode());//订单号
                            goodsSellOutStatus.setGoodssellrecordid(goodsSellRecord1.getId());//订单id
                            goodsSellOutStatus.setCreatetime(new Date());

                            RunfastGoodsSellOutStatusExample example=new RunfastGoodsSellOutStatusExample();
                            example.createCriteria().andGoodssellrecordcodeEqualTo(goodsSellRecord1.getOrdercode());
                            runfastGoodsSellOutStatusService.insert(goodsSellOutStatus);
                            runfastGoodsSellRecordService.updateByPrimaryKeySelective(goodsSellRecord1);
                            //if(diaoDuWebsocketController.webSockets !=null &&diaoDuWebsocketController.webSockets.size()>0){
                                //diaoDuWebsocketController.broadcast(goodsSellRecord1, null,null);
                            amqpTemplate.convertAndSend("waimaiServer_order_exchange", "", JSON.toJSONString(goodsSellRecord1));
                            //}
                            waiMaiMessagePushTask.takenOrderToBusiness(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getBusinessid(),"平台已为您拒单！");
                            waiMaiMessagePushTask.takenOrderToCustomer(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getUserid(),"商家已拒单！");
                            if(goodsSellRecord1.getShopperid()!=null){
                                waiMaiMessagePushTask.takenOrderToShopper(goodsSellRecord1.getOrdercode(),goodsSellRecord1.getShopperid(),"商家已拒单！");
                            }
                        }
                    }
                }

            }
       }
    return Result.ok(null);
   }











    /**跑腿调度页面需要的*/
    /**订单调度页面*/
    @GetMapping("/paotuiOrderSchedulingList")
    public  Result paotuiOrderSchedulingList(){
        //订单状态编码 0：下单，1：取消  2：付款  3：骑手接单   4：完成 ，5：已取货
        //待指派，配送中，异常，超时
        //待指派--骑手未接单
        //代理商登录就是该代理商下所有的订单，后台登录要先指定代理商
        //list1---待指派
        List<Order> list1=new ArrayList<Order>();
        //list2---配送中
        List<Order> list2=new ArrayList<Order>();
        //list3--异常
        List<Order> list3=new ArrayList<Order>();
        //list4--超时
        List<Order> list4=new ArrayList<Order>();
        WaiMaiRunfastAgentbusiness agentbusiness=new WaiMaiRunfastAgentbusiness();
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        Map<Object,Object> map1=new HashMap<Object, Object>();
        Map<Object,Object> map2=new HashMap<Object, Object>();
        Map<Object,Object> map3=new HashMap<Object, Object>();
        Map<Object,Object> map4=new HashMap<Object, Object>();
        if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商登录
            agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
            if(agentbusiness!=null){
                map1.put("agentId",agentAccounts.getAgentid());
                map2.put("agentId",agentAccounts.getAgentid());
                map3.put("agentId",agentAccounts.getAgentid());
                map4.put("agentId",agentAccounts.getAgentid());
                WaiMaiRunfastDeliverCostExample example1=new WaiMaiRunfastDeliverCostExample();
                example1.createCriteria().andAgentidEqualTo(agentAccounts.getAgentid()).andIsdefaultEqualTo(1);
                List<WaiMaiRunfastDeliverCost> deliverCostList =waiMaiRunfastDeliverCostService.selectByExample(example1);
                if(deliverCostList.size()>0){
                    if(deliverCostList.get(0).getStarttimeday1()!=null && deliverCostList.get(0).getEndtimeday1()!=null){
                        agentbusiness.setFirstTime(TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getStarttimeday1())+","+TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getEndtimeday1()));
                    }
                    if(deliverCostList.get(0).getStarttimenight2()!=null && deliverCostList.get(0).getEndtimenight2()!=null){
                        agentbusiness.setSecondTime(TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getStarttimenight2())+","+TimeUtil.getHourAndMinuteToString(deliverCostList.get(0).getEndtimenight2()));
                    }
                }
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else if(admin !=null && admin.getType()==1){
            //后台登录---获取代理商list中第一个
        }
        /**selectType:1待指派，2配送中，3异常，4超时*/
        map1.put("selectType",1);
        list1=orderService.selectByMapDiaoDu(map1);
        if(list1.size()>0){
            for(Order  order:list1){
                orderService.findFromAndTo(order);
            }
        }
        map2.put("selectType",2);
        list2=orderService.selectByMapDiaoDu(map2);
        if(list2.size()>0){
            for(Order  order:list2){
                orderService.findFromAndTo(order);
            }
        }
        map3.put("selectType",3);
        list3=orderService.selectByMapDiaoDu(map3);
        if(list3.size()>0){
            for(Order  order:list3){
                orderService.findFromAndTo(order);
            }
        }
        map4.put("selectType",4);
        list4=orderService.selectByMapDiaoDu(map4);
        if(list4.size()>0){
            for(Order  order:list4){
                orderService.findFromAndTo(order);
            }
        }
        //是否支付； 1：已支付， 其他未支付---isPay
        //用户提出取消订单 1:用户提出 2:商家同意取消订单3:不同意取消订单-----isCancel
        //配送中---骑手接单（待到店，待取餐，待送达）
        //异常-----用户申请退款（商家或后台都未处理）
        //超时
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list1",list1);
        map.put("list2",list2);
        map.put("list3",list3);
        map.put("list4",list4);
        map.put("total1",list1.size());
        map.put("total2",list2.size());
        map.put("total3",list3.size());
        map.put("total4",list4.size());
        map.put("agentbusiness",agentbusiness);
        return Result.ok(null,map);
    }

    /**
     * 跑腿订单：修改订单状态
     * */
    @GetMapping("/paotuiEditOrderStatus")
    public  Result paotuiEditOrderStatus(Order order) {
        String  message=null;
        if(order!=null && order.getId()!=null && order.getStatus()!=null){
            Order t  = orderService.selectByPrimaryKey(order.getId());
            //添加操作记录
            OrderStatusHistory orderStatusHistory=new OrderStatusHistory();
            if(order.getStatus()==PICKED){
                orderStatusHistory.setCreateTime(new Date());
                orderStatusHistory.setStatus(PICKED);
                orderStatusHistory.setOrderId(t.getId());
                orderStatusHistory.setUpdateTime(new Date());
                orderStatusHistoryService.insert(orderStatusHistory);
                t.setStatus(PICKED);
                message="骑手取货!";
            }else if(order.getStatus()==COMPLETED){
                orderStatusHistory.setCreateTime(new Date());
                orderStatusHistory.setStatus(COMPLETED);
                orderStatusHistory.setOrderId(t.getId());
                orderStatusHistory.setUpdateTime(new Date());
                orderStatusHistoryService.insert(orderStatusHistory);
                t.setStatus(COMPLETED);
                message="完成!";
            }
            orderService.updateByPrimaryKeySelective(t);
            //if(paoTuiDiaoDuWebsocketController.webSockets1 !=null &&paoTuiDiaoDuWebsocketController.webSockets1.size()>0){
            amqpTemplate.convertAndSend("paotuiServer_order_exchange", "", JSON.toJSONString(t));
               // paoTuiDiaoDuWebsocketController.paotuiBroadcast(null, null,t);
            //}
            waiMaiMessagePushTask.takenOrderToCustomer(t.getOrderNo(),t.getCuserId(),message);
        }else{return Result.fail(null,"传入参数不对！");}
        return  Result.ok(null);
    }


    /**
     *跑腿订单：给骑手派单（新单第一次指派）
     * */
    @PostMapping("/paotuiSetRiderOrder")
    public Result paotuiSetRiderOrder(@RequestBody Order order){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        if(order.getIds().size()>0  && order.getDriverId()!=null) {
            WaiMaiRunfastShopper shopper = waiMaiRunfastShopperService.selectByPrimaryKey(order.getDriverId());
            if(shopper!=null){
                for(Integer s:order.getIds()){
                    Order t=orderService.selectByPrimaryKey(s);
                    if(t!=null){
                        if(agentAccounts!=null&&!agentAccounts.getAgentid().equals(t.getAgentId())){
                            return  Result.fail(null,"只能修改自己名下商家的订单！");
                        }
                        if(shopper!=null && (shopper.getStatus()!=null && shopper.getStatus()==-1) && (shopper.getWorking()!=null && shopper.getWorking()!=1)){
                            return  Result.fail(null,"骑手无法接单，请另选一个！");
                        }
                        if(t.getDriverId()!=null){
                            return Result.fail(null,"已经有骑手接单，不能再指派骑手！");
                        }
                        if(shopper.getDistributionmun()==null){
                            shopper.setDistributionmun(5);
                        }
                        RunfastGoodsSellRecordExample recordExample2=new RunfastGoodsSellRecordExample();
                        recordExample2.createCriteria().andShopperidEqualTo(shopper.getId()).andStatusBetween(1,7).andCreatetimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                        Integer totalNum2=runfastGoodsSellRecordService.countByExample(recordExample2);
                        OrderExample recordExample3=new OrderExample();
                        List<Integer> s1=new ArrayList<Integer>();
                        s1.add(3);
                        s1.add(5);
                        recordExample3.createCriteria().andDriverIdEqualTo(shopper.getId()).andStatusIn(s1).andCreateTimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                        Integer totalNum3=orderService.countByExample(recordExample3);
                        Integer totalNum=0;
                        totalNum=totalNum2+totalNum3;
                        if(shopper.getDistributionmun()<=totalNum){
                            return Result.fail(null,"已达到该骑手当日最大配送量（"+shopper.getDistributionmun()+"单），不能再给该骑手派单！");
                        }
                        t.setDriverId(shopper.getId());
                        //订单状态记录
                        OrderStatusHistory orderStatusHistory=new OrderStatusHistory();
                        orderStatusHistory.setCreateTime(new Date());
                        orderStatusHistory.setUpdateTime(new Date());
                        orderStatusHistory.setStatus(TAKEN);
                        orderStatusHistory.setOrderId(t.getId());
                        orderStatusHistoryService.insert(orderStatusHistory);
                        t.setStatus(TAKEN);
                        t.setTimeTaken(new Date());
                        orderService.updateByPrimaryKeySelective(t);
                        //if(paoTuiDiaoDuWebsocketController.webSockets1 !=null &&paoTuiDiaoDuWebsocketController.webSockets1.size()>0){
                        amqpTemplate.convertAndSend("paotuiServer_order_exchange", "", JSON.toJSONString(t));
                        amqpTemplate.convertAndSend("server_shopper_exchange", "", JSON.toJSONString(shopper));
                            //paoTuiDiaoDuWebsocketController.paotuiBroadcast(null, null,t);
                            //paoTuiDiaoDuWebsocketController.paotuiBroadcast(null, shopper,null);
                       // }
                        waiMaiMessagePushTask.takenOrderToCustomer(t.getOrderNo(),t.getCuserId(),"骑手已接单！");
                        waiMaiMessagePushTask.takenOrderToShopper(t.getOrderNo(),shopper.getId(),"已经派单给您！");
                    }
                }
            }else{return Result.fail(null,"找不到对应的骑手！");}
        }else{return Result.fail(null,"订单id，或骑手id为空！");}
        return  Result.ok(null);
    }

    /**
     *跑腿订单：改派骑手（已经有所属的骑手但其未接单：改派）
     * */
    @GetMapping("/paotuiEditOrderRider")
    public Result paotuiEditOrderRider(Order order){
        WaiMaiRunfastShopper shopper =new WaiMaiRunfastShopper();
                BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        if(order!=null && order.getId()!=null&& order.getDriverId()!=null ){
            Order t  = orderService.selectByPrimaryKey(order.getId());
            if(t!=null && t.getDriverId()!=null && order.getDriverId()!=null&&t.getStatus()!=null && (t.getStatus()==TAKEN || t.getStatus()==PICKED)){

                if(agentAccounts!=null&&!agentAccounts.getAgentid().equals(t.getAgentId())){
                    return  Result.fail(null,"只能修改自己名下商家的订单！");
                }
                if(!t.getDriverId().equals(order.getDriverId())){
                    shopper = waiMaiRunfastShopperService.selectByPrimaryKey(order.getDriverId());
                    if(shopper!=null && (shopper.getStatus()!=null && shopper.getStatus()==-1) && (shopper.getWorking()!=null && shopper.getWorking()!=1)){
                        return  Result.fail(null,"骑手无法接单，请另选一个！");
                    }
                    /*if(t.getDriverId()!=null){
                        if(t.getDriverId().equals(shopper.getId())){
                            return Result.fail(null,"自己的订单不能改派给自己！");
                        }
                    }*/
                    if(shopper.getDistributionmun()==null){
                        shopper.setDistributionmun(5);
                    }
                    RunfastGoodsSellRecordExample recordExample2=new RunfastGoodsSellRecordExample();
                    recordExample2.createCriteria().andShopperidEqualTo(shopper.getId()).andStatusBetween(1,7).andCreatetimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                    Integer totalNum2=runfastGoodsSellRecordService.countByExample(recordExample2);
                    OrderExample recordExample3=new OrderExample();
                    List<Integer> s1=new ArrayList<Integer>();
                    s1.add(3);
                    s1.add(5);
                    recordExample3.createCriteria().andDriverIdEqualTo(shopper.getId()).andStatusIn(s1).andCreateTimeBetween(com.runfast.waimai.web.controller.shopper.TimeUtil.getStartTime(), com.runfast.waimai.web.controller.shopper.TimeUtil.getEndTime());
                    Integer totalNum3=orderService.countByExample(recordExample3);
                    Integer totalNum=0;
                    totalNum=totalNum2+totalNum3;
                    if(shopper.getDistributionmun()<=totalNum){
                        return Result.fail(null,"已达到该骑手当日最大配送量（"+shopper.getDistributionmun()+"单），不能再给该骑手派单！");
                    }
                    //更换新的现有配送员
                    t.setDriverId(order.getDriverId());
                }else{
                    return  Result.fail(null,"自己的订单不能改派给自己！");
                }
            }else{
                return  Result.fail(null,"您没有更换到骑手！");
            }
            orderService.updateByPrimaryKeySelective(t);
            //if(paoTuiDiaoDuWebsocketController.webSockets1 !=null &&paoTuiDiaoDuWebsocketController.webSockets1.size()>0){
                //paoTuiDiaoDuWebsocketController.paotuiBroadcast(null, null,t);
            amqpTemplate.convertAndSend("paotuiServer_order_exchange", "", JSON.toJSONString(t));
            amqpTemplate.convertAndSend("server_shopper_exchange", "", JSON.toJSONString(shopper));
            //}
            waiMaiMessagePushTask.takenOrderToCustomer(t.getOrderNo(),t.getCuserId(),"已为您更换骑手！");
            waiMaiMessagePushTask.takenOrderToShopper(t.getOrderNo(),t.getCuserId(),"已经派单给您！");
        }
        return  Result.ok(null);
    }
}
